package top.ywlog.permission.service;

import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import top.ywlog.permission.common.RequestHolder;
import top.ywlog.permission.common.request.DeptParam;
import top.ywlog.permission.dao.SysDeptMapper;
import top.ywlog.permission.exception.ParamException;
import top.ywlog.permission.model.SysDept;
import top.ywlog.permission.util.IpUtils;
import top.ywlog.permission.util.LevelUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author Durian
 */
@Slf4j
@Validated
@Service
public class SysDeptService
{
    @Resource
    private SysDeptMapper sysDeptMapper;

    @Transactional
    public void save(DeptParam param)
    {
        if (checkExist(param.getParentId(), param.getName(), param.getId()))
        {
            log.error("同一层级下存在相同名称的部门:{}", param);
            throw new ParamException("同一层级下存在相同名称的部门");
        }
        SysDept dept = SysDept.builder().name(param.getName()).parentId(param.getParentId())
                .seq(param.getSeq()).remark(param.getRemark()).build();

        dept.setLevel(LevelUtils.calculateLevel(getLevel(param.getParentId()), param.getParentId()));
        dept.setOperator(RequestHolder.getCurrentUser().getUsername());
        dept.setOperateIp(IpUtils.getRemoteIp(RequestHolder.getCurrentRequest()));
        dept.setOperateTime(LocalDateTime.now());
        sysDeptMapper.insertSelective(dept);
    }

    @Transactional
    public void update(DeptParam param)
    {
        if (checkExist(param.getParentId(), param.getName(), param.getId()))
        {
            log.error("同一层级下存在相同名称的部门:{}", param);
            throw new ParamException("同一层级下存在相同名称的部门");
        }
        SysDept before = sysDeptMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before, "待更新的部门不存在");

        // 设置新值
        SysDept after = SysDept.builder().id(param.getId()).name(param.getName()).parentId(param.getParentId())
                .seq(param.getSeq()).remark(param.getRemark()).build();
        after.setLevel(LevelUtils.calculateLevel(getLevel(param.getParentId()), param.getParentId()));
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtils.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(LocalDateTime.now());
        // 更新
        updateWithChild(before, after);
    }


    private void updateWithChild(SysDept before, SysDept after)
    {
        String newLevel = after.getLevel();
        String oldLevel = before.getLevel();
        // 当更新后的部门层级变化时，才更新子部门
        if (!Objects.equals(after.getLevel(), before.getLevel()))
        {
            // 获取所有子部门
            List<SysDept> childDeptList = sysDeptMapper.getChildDeptListByLevel(before.getLevel());
            if (CollectionUtils.isNotEmpty(childDeptList))
            {
                for (SysDept childDept : childDeptList)
                {
                    // 子部门层级
                    String childLevel = childDept.getLevel();
                    /* 0.1.2 -->  0.1   */
                    if (childLevel.indexOf(oldLevel) == 0)
                    {
                        childLevel = newLevel + childLevel.substring(oldLevel.length());
                        childDept.setLevel(childLevel);
                    }
                }
                // 批量更新子部门
                sysDeptMapper.batchUpdateLevel(childDeptList);
            }
        }
        // 只更新当前部门
        sysDeptMapper.updateByPrimaryKey(after);
    }


    @Transactional
    public void delete(int deptId)
    {
        SysDept dept = sysDeptMapper.selectByPrimaryKey(deptId);
        if (dept == null)
        {
            log.error("待删除的部门不存在，无法删除 deptId:{}", deptId);
            throw new ParamException("待删除的部门不存在，无法删除");
        }
        if (sysDeptMapper.countByParentId(dept.getId()) > 0)
        {
            log.error("当前部门下面有子部门，无法删除ID为{}的部门", deptId);
            throw new ParamException("当前部门下面有子部门，无法删除");
        }
        /*if (sysUserMapper.countByDeptId(dept.getId()) > 0)
        {
            throw new ParamException("当前部门下面有用户，无法删除");
        }*/
        sysDeptMapper.deleteByPrimaryKey(deptId);
    }

    private boolean checkExist(Integer parentId, String deptName, Integer deptId)
    {
        return sysDeptMapper.countByNameAndParentId(parentId, deptName, deptId) > 0;
    }

    private String getLevel(Integer deptId)
    {
        SysDept dept = sysDeptMapper.selectByPrimaryKey(deptId);
        if (dept == null)
        {
            return null;
        }
        return dept.getLevel();
    }
}
